// 字符串去除所有空格
export const trim = (str: string) => str.replace(/\s+/g, '')

// 字符串去除前空格
export const ltrim = (str: string) => str.replace(/^\s+/g, '')

// 字符串去除尾空格
export const rtrim = (str: string) => str.replace(/\s+$/g, '')

export declare type GenerateRandomCode = {
  (): string
  (len: number): string
  (len: number, uppercase: boolean): string
  (len: number, uppercase: boolean, symbols: boolean): string
  (len: number, uppercase: boolean, symbols: boolean, excludes: string): string
  (len: number, uppercase: boolean, symbols: boolean, excludes: string, includes: string): string
}

// 随机生成指定位数字符串
export const generateRandomCode: GenerateRandomCode = (len?: number, uppercase?: boolean, symbols?: boolean, excludes?: string, includes?: string) => {
  len = len || 8

  const uppercaseChars = uppercase ? 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' : ''

  const lowercaseChars = 'abcdefghijklmnopqrstuvwxyz'

  const numbersChars = '0123456789'

  const symbolsChars = symbols ? '!@#$%^&*()_+-=[]{}|;:,.<>?/' : ''

  let chars = `${uppercaseChars}${lowercaseChars}${numbersChars}${symbolsChars}`

  // 需要排除的字符
  if (excludes && excludes.length) {
    excludes.split('').forEach(exclude => {
      chars = chars.replace(exclude, '')
    })
  }

  // 需要追加的字符
  if (includes && includes.length) {
    includes.split('').forEach(include => {
      if (!chars.includes(include)) chars = chars.concat(include)
    })
  }

  const length = chars.length

  let code = ''

  let i = 0

  while (i < len) {
    code += chars.charAt(Math.floor(Math.random() * length))
    i++
  }

  return code
}
